/**
 * 王国系统
 */
const KingdomSystem = {
    /**
     * 更新所有王国
     */
    updateKingdoms() {
        GameData.kingdoms.forEach(kingdom => {
            // 更新人口
            this.updatePopulation(kingdom);
            
            // 更新资源
            this.updateResources(kingdom);
            
            // 更新军事力量
            this.updateMilitary(kingdom);
            
            // 更新状态
            this.updateStatus(kingdom);
        });
    },
    
    /**
     * 更新王国人口
     * @param {Object} kingdom - 王国对象
     */
    updatePopulation(kingdom) {
        const race = GameData.getRaceById(kingdom.raceId);
        
        // 如果是亡灵族且有特殊人口规则
        if (race.id === 5 && race.effects.populationGrowth < 0) {
            // 亡灵族不增长，但也不会自然减少
            return;
        }
        
        // 计算基础增长率
        let growthRate = CONFIG.KINGDOM.BASE_GROWTH_RATE;
        
        // 应用种族修正
        if (race.effects.populationGrowth) {
            growthRate += race.effects.populationGrowth;
        }
        
        // 应用地形修正
        const terrainType = this.getKingdomTerrainType(kingdom);
        const terrainEffects = CONFIG.MAP.TERRAIN_TYPES[terrainType].effects;
        if (terrainEffects.population) {
            growthRate += terrainEffects.population;
        }
        
        // 计算人口变化
        const populationChange = Math.floor(kingdom.population * growthRate);
        
        // 更新人口
        kingdom.population += populationChange;
        
        // 确保人口不为负
        kingdom.population = Math.max(0, kingdom.population);
        
        // 如果王国已达到最大半径，停止人口增长
        const currentRadius = 15 + Math.sqrt(kingdom.population) / 10;
        if (currentRadius >= CONFIG.MAP.MAX_KINGDOM_RADIUS) {
            kingdom.population = Math.pow((CONFIG.MAP.MAX_KINGDOM_RADIUS - 15) * 10, 2);
        }
        
        // 如果人口变化显著，添加日志
        if (Math.abs(populationChange) > kingdom.population * 0.05) {
            const message = populationChange > 0 
                ? `${kingdom.name}人口大幅增长，新增${Utils.formatNumber(populationChange)}人口`
                : `${kingdom.name}人口大幅减少，损失${Utils.formatNumber(Math.abs(populationChange))}人口`;
            
            Utils.addLogEntry(message, populationChange > 0 ? 'positive' : 'important');
        }
    },
    
    /**
     * 更新王国资源
     * @param {Object} kingdom - 王国对象
     */
    updateResources(kingdom) {
        const race = GameData.getRaceById(kingdom.raceId);
        
        // 基础资源生产
        let resourceGeneration = kingdom.population * CONFIG.KINGDOM.RESOURCE_GENERATION.PER_POPULATION;
        
        // 计算王国控制的资源点
        const controlledResources = this.getControlledResourcePoints(kingdom);
        resourceGeneration += controlledResources.length * CONFIG.KINGDOM.RESOURCE_GENERATION.PER_RESOURCE_POINT;
        
        // 应用种族修正
        if (race.effects.resourceGathering) {
            resourceGeneration *= (1 + race.effects.resourceGathering);
        }
        
        // 应用地形修正
        const terrainType = this.getKingdomTerrainType(kingdom);
        const terrainEffects = CONFIG.MAP.TERRAIN_TYPES[terrainType].effects;
        if (terrainEffects.resources) {
            resourceGeneration *= (1 + terrainEffects.resources);
        }
        
        // 更新资源
        kingdom.resources += Math.floor(resourceGeneration);
    },
    
    /**
     * 更新王国军事力量
     * @param {Object} kingdom - 王国对象
     */
    updateMilitary(kingdom) {
        const race = GameData.getRaceById(kingdom.raceId);
        
        // 基础军事力量
        let militaryGeneration = kingdom.population * CONFIG.KINGDOM.MILITARY_GENERATION.PER_POPULATION;
        
        // 计算王国的强者数量
        const kingdomHeroes = GameData.strongestList.filter(
            item => GameData.npcs[item.npc.id] && GameData.npcs[item.npc.id].raceId === kingdom.raceId
        );
        
        militaryGeneration += kingdomHeroes.length * CONFIG.KINGDOM.MILITARY_GENERATION.PER_HERO;
        
        // 应用种族修正
        if (race.effects.militaryPower) {
            militaryGeneration *= (1 + race.effects.militaryPower);
        }
        
        // 应用地形修正
        const terrainType = this.getKingdomTerrainType(kingdom);
        const terrainEffects = CONFIG.MAP.TERRAIN_TYPES[terrainType].effects;
        if (terrainEffects.military) {
            militaryGeneration *= (1 + terrainEffects.military);
        }
        
        // 更新军事力量
        kingdom.military += Math.floor(militaryGeneration);
    },
    
    /**
     * 更新王国状态
     * @param {Object} kingdom - 王国对象
     */
    updateStatus(kingdom) {
        // 根据资源和人口比例确定状态
        const resourcePerCapita = kingdom.resources / kingdom.population;
        
        if (resourcePerCapita > 2) {
            kingdom.status = "繁荣";
        } else if (resourcePerCapita > 1) {
            kingdom.status = "稳定";
        } else if (resourcePerCapita > 0.5) {
            kingdom.status = "动荡";
        } else {
            kingdom.status = "衰退";
        }
        
        // 如果状态发生变化，添加日志
        if (kingdom.prevStatus && kingdom.prevStatus !== kingdom.status) {
            Utils.addLogEntry(`${kingdom.name}状态变为"${kingdom.status}"`, kingdom.status === "繁荣" ? 'positive' : 'normal');
        }
        
        kingdom.prevStatus = kingdom.status;
    },
    
    /**
     * 获取王国所在的主要地形类型
     * @param {Object} kingdom - 王国对象
     * @returns {string} 地形类型
     */
    getKingdomTerrainType(kingdom) {
        const x = Math.floor(kingdom.location.x);
        const y = Math.floor(kingdom.location.y);
        
        // 确保坐标在地图范围内
        if (x >= 0 && x < CONFIG.MAP.WIDTH && y >= 0 && y < CONFIG.MAP.HEIGHT) {
            const terrainY = Math.floor(y / CONFIG.MAP.HEIGHT * GameData.map.terrain.length);
            const terrainX = Math.floor(x / CONFIG.MAP.WIDTH * GameData.map.terrain[0].length);
            
            if (terrainY >= 0 && terrainY < GameData.map.terrain.length && 
                terrainX >= 0 && terrainX < GameData.map.terrain[0].length) {
                return GameData.map.terrain[terrainY][terrainX];
            }
        }
        
        // 默认返回平原
        return 'PLAINS';
    },
    
    /**
     * 获取王国控制的资源点
     * @param {Object} kingdom - 王国对象
     * @returns {Array} 资源点数组
     */
    getControlledResourcePoints(kingdom) {
        const controlRadius = 50 + Math.sqrt(kingdom.population) / 5;
        
        return GameData.map.resourcePoints.filter(point => {
            const dx = point.x - kingdom.location.x;
            const dy = point.y - kingdom.location.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            return distance <= controlRadius;
        });
    },
    
    /**
     * 玩家干预：发展经济
     * @param {Object} kingdom - 王国对象
     */
    developEconomy(kingdom) {
        // 消耗军事力量来提升资源
        const militaryCost = Math.floor(kingdom.military * 0.2);
        const resourceGain = militaryCost * 2;
        
        kingdom.military -= militaryCost;
        kingdom.resources += resourceGain;
        
        Utils.addLogEntry(`${kingdom.name}发展经济，消耗${Utils.formatNumber(militaryCost)}军事力量，获得${Utils.formatNumber(resourceGain)}资源`, 'positive');
    },
    
    /**
     * 玩家干预：扩充军备
     * @param {Object} kingdom - 王国对象
     */
    expandMilitary(kingdom) {
        // 消耗资源来提升军事力量
        const resourceCost = Math.floor(kingdom.resources * 0.2);
        const militaryGain = resourceCost * 1.5;
        
        kingdom.resources -= resourceCost;
        kingdom.military += militaryGain;
        
        Utils.addLogEntry(`${kingdom.name}扩充军备，消耗${Utils.formatNumber(resourceCost)}资源，获得${Utils.formatNumber(militaryGain)}军事力量`, 'positive');
    },
    
    /**
     * 玩家干预：探索资源
     * @param {Object} kingdom - 王国对象
     */
    exploreResources(kingdom) {
        // 消耗人口和军事力量来寻找新资源点
        const populationCost = Math.floor(kingdom.population * 0.05);
        const militaryCost = Math.floor(kingdom.military * 0.1);
        
        kingdom.population -= populationCost;
        kingdom.military -= militaryCost;
        
        // 50%概率发现新资源点
        if (Utils.chance(0.5)) {
            // 在王国附近创建新资源点
            const angle = Math.random() * Math.PI * 2;
            const distance = Utils.randomInt(30, 80);
            const newResourcePoint = {
                x: kingdom.location.x + Math.cos(angle) * distance,
                y: kingdom.location.y + Math.sin(angle) * distance
            };
            
            GameData.map.resourcePoints.push(newResourcePoint);
            
            Utils.addLogEntry(`${kingdom.name}探索成功，发现了新的资源点！`, 'positive');
        } else {
            Utils.addLogEntry(`${kingdom.name}探索失败，损失了${Utils.formatNumber(populationCost)}人口和${Utils.formatNumber(militaryCost)}军事力量`, 'important');
        }
    }
};